use model_graph_channel::data_channels::request::ping;
use model_graph_common::transport::rrai::{rrai_cloud_get, rrai_cloud_post};
use model_graph_types::peer::{get_peer_id, get_token, is_self};

use crate::transport::{exist_connection, prepare_follower};

use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
struct Device {
    peer_id: String,
    dtype: String,
    is_online: u16,
}

pub async fn device_net_group() -> anyhow::Result<()> {
    //获取所有的设备
    let token = get_token()?;
    let devices_str = rrai_cloud_post(
        &String::from("/devices/device/search"),
        &token,
        serde_json::to_string(&serde_json::json!({}))?,
    )
    .await?;

    //解析json
    let devices: Vec<Device> = serde_json::from_str(devices_str.as_str())
        .map_err(|err| anyhow::anyhow!("JSON解析失败:{}\n{}", err, devices_str))?;

    let self_peer = get_peer_id()?;

    for peer in devices {
        if is_self(&peer.peer_id)? {
            // tracing::debug!("节点不在线或者是自身!{}", &peer.peer_id);
            continue;
        }
        if peer.is_online != 1 {
            // tracing::debug!("节点不在线或者是自身!{}", &peer.peer_id);
            continue;
        }
        if exist_connection(&peer.peer_id)? {
            tracing::debug!("连接存在!{}", &peer.peer_id);
            let _ = ping(&peer.peer_id).await;
            continue;
        }
        //如果自身的peer id > 对方的
        if self_peer > peer.peer_id {
            if let Err(err) = prepare_follower(&peer.peer_id).await {
                tracing::error!("{}建立数据通道请求失败!{}", &peer.peer_id, err);
            }
        }
    }

    Ok(())
}
